<template>
  <div>
    <div class="nav">
      <div class="nav-content">
        <el-row :gutter="20">
          <el-col :span="2">
            <router-link to="/">
              <img class="logo" src="../assets/logo.jpg" alt="chenyiwei" />
            </router-link>
          </el-col>

          <el-col :span="12">
            <el-menu
              :router="true"
              :default-active="state.activeIndex"
              active-text-color="#409eff"
              class="el-menu-demo"
              mode="horizontal"
              @select="handleSelect"
            >
              <el-menuItem
                :route="l.path"
                :index="l.index"
                v-for="l in state.list"
                :key="l.index"
              >
                {{ l.name }}
              </el-menuItem>
            </el-menu>
          </el-col>

          <el-col :span="5">
            <div class="search">
              <Search />
            </div>
          </el-col>
          <!-- 这一列是登录后的样式 -->
          <el-col v-if="userInfo._id" :span="5">
            <div class="nav-right">
              <!-- <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  Dropdown List<el-icon class="el-icon--right"
                    ><arrow-down
                  /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="a">Action 1</el-dropdown-item>
                    <el-dropdown-item command="b">Action 2</el-dropdown-item>
                    <el-dropdown-item command="c">Action 3</el-dropdown-item>
                    <el-dropdown-item command="d" disabled
                      >Action 4</el-dropdown-item
                    >
                    <el-dropdown-item command="e" divided
                      >Action 5</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown> -->
              <el-dropdown @command="handleLogout">
                <span class="el-dropdown-link">
                  {{ userInfo.name }}
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <img class="logo" src="../assets/logo.jpg" alt="chenyiwei" />
                <!-- <img
                  v-if="!userInfo.avatar"
                  class="user-img"
                  src="../assets/logo.jpg"
                  alt="cyw"
                />
                <img
                   v-if="userInfo.avatar"
                   class="user-img"
                   src="../assets/logo.jpg"
                  alt="cyw"
                 
                /> -->
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="logout">登 出</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-col>
          <el-col v-else :span="4">
            <div class="nav-right">
              <el-button
                size="small"
                type="primary"
                @click="handleClick('login')"
                >登录</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleClick('register')"
                >注册</el-button
              >
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 下面这些是客户端的布局 -->
    <!-- <div
      class="nav"
    >
      <div class="nav-mobile">
        <div class="nav-mobile-logo">
          <router-link to="/">
             <img
              class="logo fl"
              src="../assets/logo.jpg"
              alt="BiaoChenXuYing"
            > 
          </router-link>
        </div>
        <div class="title">{{}}</div>
        <div
          class="menu"
          @click="handleMenu"
        ><i class="el-icon-menu"></i></div>
      </div>
      <div
        class="nav-mobile-content"
      >
        <div class="list">
          <div
            @click="handleClickMenu('')"
            class="item"
          >
            <router-link to="/">首 页</router-link>
          </div>
          <div
            @click="handleClickMenu('/articles')"
            class="item"
          >
            <router-link to="/articles">文 章</router-link>
          </div>
          <div
            @click="handleClickMenu('/archive')"
            class="item"
          >
            <router-link to="/archive">归 档</router-link>
          </div>
          <div
            @click="handleClickMenu('/project')"
            class="item"
          >
            <router-link to="/project">项 目</router-link>
          </div>
          <div
            @click="handleClickMenu('/timeline')"
            class="item"
          >
            <router-link to="/timeline">历 程</router-link>
          </div>
          <div
            @click="handleClickMenu('/message')"
            class="item"
          >
            <router-link to="/message">留 言</router-link>
          </div>
          <div
            @click="handleClickMenu('/about')"
            class="item"
          >
            <router-link to="/about">关 于</router-link>
          </div>
          <div
            @click="handleClickMenu('/login')"
            class="item"
          >
             <span v-if="userInfo._id">{{ userInfo.name }}</span> 
            <span >登 录</span>
          </div>
          <div
            @click="handleClickMenu('/register')"
            class="item"
          >
            注 册
          </div>
          <div
            @click="handleClickMenu('/logout')"
            class="item"
          >
            登 出
          </div>
        </div>
      </div>
    </div> -->
    <!-- class="mask" -->
    <div @click="handleHideMenu"></div>
    <LoginOrRegister
      :visible="state.visible"
      :type="state.type"
      @submit="handleOk"
      @cancel="handleCancel"
    ></LoginOrRegister>
  </div>
</template>

<script setup lang="ts">
import Search from "../components/Search.vue";
// import { key } from "../store";
import { useStore } from "vuex";
import LoginOrRegister from "./LoginOrRegister.vue";
import { NavListItem, UserInfo } from "../type/index";
import { reactive, watch, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const store = useStore();
const store1 = useStore();
const state = reactive({
  visible: false, //表单是否可见
  type: "", //值是登录或注册
  title: "首页",
  list: [
    {
      index: "1",
      path: "/",
      name: "首页",
    },
    {
      index: "2",
      path: "/articles",
      name: "全部",
    },
    {
      index: "3",
      path: "/my",
      name: "我的文章",
    },
    {
      index: "4",
      path: "/edit",
      name: "编辑",
    },
    {
      index: "5",
      path: "/archive",
      name: "归档",
    },
    {
      index: "6",
      path: "/project",
      name: "项目",
    },
    {
      index: "7",
      path: "/message",
      name: "留言",
    },
  ] as Array<NavListItem>,
  activeIndex: "0",
  enterSlideUp: false,
  leaveSlideDown: false,
  isShow: false,
  //   isMobile: isMobileOrPc(),
});

const handleClick = (value: string): void => {
  //  console.log(value)
  state.type = value;
  state.visible = true;
};
const handleCancel = (value: boolean): void => {
  state.visible = value;
};
const handleSelect = (val: string, oldVal: string) => {
  state.activeIndex = val;
};
const handleOk = (value: boolean): void => {
  state.visible = value;
};
// 退出登录
const handleLogout = (): void => {
  window.localStorage.userInfo = "";
  store.commit("saveUser", {
    userInfo: {
      _id: "",
      name: "",
      avatar: "",
    },
  });
};

//pc端的切换路由
const handleClickMenu = (route?: string): void => {
  state.isShow = false;
  if (route === "/login") {
    state.type = "login";
    state.visible = true;
  }
  if (route === "/register") {
    state.type = "register";
    state.visible = true;
  }
  if (route === "/logout") {
    // handleLogout();
  }
};
//移动端的切换路由的动画效果
const handleMenu = (): void => {
  state.isShow = true;
  state.enterSlideUp = true;
};
const handleHideMenu = (): void => {
  state.enterSlideUp = false;
  state.leaveSlideDown = true;
  setTimeout(() => {
    state.leaveSlideDown = false;
    state.isShow = false;
  }, 300);
};

//记录当前的页面路由和名称
const routeChange = (val: any, oldVal: any) => {
  for (let i = 0; i < state.list.length; i++) {
    const item: NavListItem = state.list[i];
    if (item.path === val.path) {
      state.activeIndex = i + 1 + "";
      state.title = item.name;
      break;
    }
  }
};

//获取用户信息  授权登录获取用户信息
// const getUser = async (code: string): Promise<void> => {
//       const loading: any = ElLoading.service({
//         lock: true,
//         text: "Loading",
//         spinner: "el-icon-loading",
//         background: "rgba(255, 255, 255, 0.7)",
//       });
//       const data: UserInfo = await service.post(
//         urls.getUser,
//         { code },
//         { withCredentials: true }
//       );
//       loading.close();

//       const userInfo: UserInfo = {
//         _id: data._id,
//         name: data.name,
//         avatar: data.avatar,
//       };
//       store.commit("SAVE_USER", {
//         userInfo,
//       });
//       window.sessionStorage.userInfo = JSON.stringify(userInfo);
//       ElMessage({
//         message: "操作成功",
//         type: "success",
//       });
//       let preventHistory = JSON.parse(window.sessionStorage.preventHistory);
//       if (preventHistory) {
//         router.push({
//           path: preventHistory.name,
//           query: preventHistory.query,
//         });
//       }
//     };

//使用watch观察路由变化，记录当前路由
watch(
  route,
  (val, oldVal) => {
    routeChange(val, oldVal);
  },
  { immediate: true }
);

//computed
let userInfo = computed((): UserInfo => {
  let userInfo = {
    _id: "",
    name: "",
    avatar: "",
  };
  if (window.localStorage.userInfo) {
    userInfo = JSON.parse(window.localStorage.userInfo);
    store.commit("saveUser", {
      userInfo,
    });
  }
  if (store.state.user.userInfo.userInfo) {
    userInfo = store.state.user.userInfo.userInfo;
  }
  console.log("用户信息", userInfo);
  // if (store.state.user.userInfo) {
  //   userInfo = store.state.user.userInfo;
  // }
  //  console.log(userInfo.avatar)
  // console.log(userInfo)
  // console.log(!userInfo.avatar)
  return userInfo;
});
// watch(
//   userInfo,
//   (val, oldVal) => {
//     console.log(oldVal);
//     console.log(val);
//   },
//   { immediate: true }
// );
onMounted(() => {
  // 授权登录的，有 code 参数
  routeChange(route, route);

  // const code: string = getQueryStringByName("code");
  // if (code) {
  //   this.getUser(code);
  // }
});
</script>

<style scoped lang="less">
.nav-mobile {
  display: flex;
  line-height: 60px;
  .nav-mobile-logo {
    flex: 1;
    margin-top: 5px;
    margin-left: 10px;
  }
  .title {
    flex: 3;
    font-size: 24px;
  }
  .menu {
    flex: 1;
    font-size: 34px;
    color: #409eff;
  }
}
.nav-mobile-content {
  font-size: 0.3rem;
  height: 7.3rem;
  width: 100%;
  background-color: #fff;
  .list {
    .item {
      line-height: 0.8rem;
      color: #303133;
      border-bottom: 1px solid #eee;
      a {
        display: block;
        width: 100%;
        color: #409eff;
        text-decoration-line: none;
      }
    }
  }
}

//pc端样式
.nav {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  width: 100%;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  .nav-content {
    width: 1200px;
    margin: 0 auto;
  }
  .logo {
    height: 50px;
    margin: 0;
    border-radius: 50%;
    margin-top: 5px;
  }
  .el-menu.el-menu--horizontal {
    border-bottom: none;
  }
  .el-menu--horizontal > .el-menu-item {
    cursor: pointer;
    color: #333;
  }
  .search {
    position: relative;
    padding-top: 12px;
  }
  .nav-right {
    position: relative;
    padding-top: 15px;
    text-align: right;
    .el-dropdown {
      cursor: pointer;
      padding-right: 60px;
    }
    .user-img {
      position: absolute;
      top: -15px;
      right: 0;
      width: 50px;
      border-radius: 50%;
    }
  }
}

//切换路由的滑动效果,移动端
.enter-slideUp,
.leave-slideDown {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1010;
}
.enter-slideUp {
  overflow: auto;
  visibility: visible;
  z-index: 1001;
  animation: slideUp 0.3s forwards;
}
.leave-slideDown {
  visibility: visible;
  z-index: 1001;
  animation: slideDown 0.3s forwards;
}

@keyframes slideUp {
  from {
    transform: translate3d(0, 100%, 0);
    opacity: 0.1;
  }
  to {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
}
@keyframes slideDown {
  from {
    transform: translate3d(0, 0, 0);
  }
  to {
    transform: translate3d(0, 100%, 0);
    opacity: 0;
  }
}
//遮罩层
.mask {
  position: fixed;
  z-index: 100;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.5;
}
.mask-fade-out {
  animation: maskFadeOut 0.4s forwards;
}
@keyframes maskFadeOut {
  from {
    opacity: 0.5;
  }
  to {
    opacity: 0;
  }
}
</style>
